package com.huanzhidadi.single.delayquit;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

@Data
@Slf4j
@AllArgsConstructor
public class UserQuitConsumer implements Runnable {

    private DelayQueue<QuitUserKey> delayQueue;

    @Override
    public void run() {
        while (true) {
            try {
                // peek返回队列头部的元素 如果队列为空，则返回null
                QuitUserKey peek = delayQueue.peek();
                if (Objects.nonNull(peek)) {
                    // 等待队列头部元素的延迟时间后再执行
                    long delay = peek.getDelay(TimeUnit.MILLISECONDS);
                    if (delay > 0) {
                        log.info("延迟队列头部元素" + peek + "还要" + delay + "ms过期");
                        Thread.sleep(delay);
                    } else {
                        // 这里没有进入
                        QuitUserKey quitUserKey = delayQueue.take();
                        log.info("用户退出 {}", quitUserKey);
                    }
                }
                // take移除并返回队列头部的元素 如果队列为空，则阻塞
                log.info("阻塞并尝试从队列中获取元素");
                QuitUserKey quitUserKey = delayQueue.take();
                log.info("用户退出 {}，{}ms过期", quitUserKey, quitUserKey.getDelay(TimeUnit.MILLISECONDS));
            } catch (Exception e) {
                log.error("消费者发生异常。", e);
            }
        }
    }
}
